<template>
  <div class="breach-list">
    <a-card>
      <div slot="title">
        <a-space>
          <div class="ty"></div>
          {{ $t("breach.list.title") }}
        </a-space>
      </div>
      <!-- 头部数据统计 -->
      <div class="header">
        <div class="card" v-for="item in cardList" :key="item.title">
          <img
            :src="require(`@/assets/svg/breach/${item.url}.svg`)"
            alt=""
            width="50"
          />
          <div class="card-right">
            <h4>{{ item.num }}</h4>
            <p>{{ $t(item.title) }}</p>
          </div>
        </div>
      </div>
    </a-card>
    <a-card class="list mt-[10px]">
      <a-button
        class="mb-[10px]"
        type="primary"
        icon="plus"
        @click="visible = true"
        >{{ $t("breach.list.content.add") }}</a-button
      >
      <a-table
        size="middle"
        class="h-full overflow-x-auto"
        :dataSource="listData"
        :scroll="{ x: 2000, y: 2000 }"
        :loading="listLoading"
        @change="getList"
        :rowKey="(record) => record.Id"
        :pagination="{ total }"
      >
        <!-- 事件ID -->
        <a-table-column
          key="EventId"
          data-index="EventId"
          width="150px"
          @filterDropdownVisibleChange="
            (e) => {
              if (e) this.setValus(1);
            }
          "
          :sorter="true"
        >
          <span slot="title">{{ $t("breach.list.content.table.id") }}</span>
          <span slot="filterDropdown" slot-scope="{ confirm }">
            <table-select
              ref="tableselect1"
              :filter-data="filterData"
              :singleSearch="true"
              @searchCommit="searchQuery"
              @searchFilter="searchQueryFilter"
              @searchClose="confirm"
              @searchClean="tableCleanJobs"
            />
          </span>
        </a-table-column>
        <!-- 泄漏事件名称 -->
        <a-table-column
          key="EventShortDescription"
          data-index="EventShortDescription"
          width="150px"
          @filterDropdownVisibleChange="
            (e) => {
              if (e) this.setValus(2);
            }
          "
          :sorter="true"
        >
          <span slot="title">{{ $t("breach.list.content.table.name") }}</span>
          <span slot="filterDropdown" slot-scope="{ confirm }">
            <table-select
              ref="tableselect2"
              :filter-data="filterData"
              :singleSearch="true"
              @searchCommit="searchQuery"
              @searchFilter="searchQueryFilter"
              @searchClose="confirm"
              @searchClean="tableCleanJobs"
            />
          </span>
        </a-table-column>
        <!-- 事件来源 -->
        <a-table-column
          key="EventTemplate"
          data-index="EventTemplate"
          width="150px"
          @filterDropdownVisibleChange="
            (e) => {
              if (e) this.setValus(3);
            }
          "
        >
          <span slot="title">{{ $t("breach.list.content.table.source") }}</span>
          <span slot="filterDropdown" slot-scope="{ confirm }">
            <table-select
              ref="tableselect3"
              :filter-data="filterData"
              :singleSearch="false"
              @searchCommit="searchQuery"
              @searchFilter="searchQueryFilter"
              @searchClose="confirm"
              @searchClean="tableCleanJobs"
            />
          </span>
          <template slot-scope="text, record">
            {{
              record.EventTemplate != "0"
                ? $t(
                    sourceList.filter(
                      (item) => item.value === record.EventTemplate
                    )[0].label
                  )
                : ""
            }}
          </template>
        </a-table-column>
        <!-- 类型 -->
        <a-table-column
          key="EventTypeStr"
          width="150px"
          @filterDropdownVisibleChange="
            (e) => {
              if (e) this.setValus(4);
            }
          "
        >
          <span slot="title">{{ $t("breach.list.content.table.type") }}</span>
          <span slot="filterDropdown" slot-scope="{ confirm }">
            <table-select
              ref="tableselect4"
              :filter-data="filterData"
              :singleSearch="false"
              @searchCommit="searchQuery"
              @searchFilter="searchQueryFilter"
              @searchClose="confirm"
              @searchClean="tableCleanJobs"
            />
          </span>
          <template slot-scope="text, record">
            {{
              lang
                ? record.EventTypeStr != 0
                  ? record.EventTypeStr
                  : ""
                : record.EventTypeStrEn != 0
                ? record.EventTypeStrEn
                : ""
            }}
          </template>
        </a-table-column>
        <!-- 处理人 -->
        <a-table-column
          key="EventProcessedStr"
          data-index="EventProcessedStr"
          width="150px"
          @filterDropdownVisibleChange="
            (e) => {
              if (e) this.setValus(5);
            }
          "
          :sorter="true"
        >
          <span slot="title">{{ $t("breach.list.content.table.owner") }}</span>
          <span slot="filterDropdown" slot-scope="{ confirm }">
            <table-select
              ref="tableselect5"
              :filter-data="filterData"
              :singleSearch="false"
              @searchCommit="searchQuery"
              @searchFilter="searchQueryFilter"
              @searchClose="confirm"
              @searchClean="tableCleanJobs"
            />
          </span>
        </a-table-column>
        <!-- 数据泄露在何处 -->
        <a-table-column
          key="EventDestination"
          data-index="EventDestination"
          width="150px"
          @filterDropdownVisibleChange="
            (e) => {
              if (e) this.setValus(6);
            }
          "
          :sorter="true"
        >
          <span slot="title">{{ $t("breach.list.content.table.where") }}</span>
          <span slot="filterDropdown" slot-scope="{ confirm }">
            <table-select
              ref="tableselect6"
              :filter-data="filterData"
              :singleSearch="false"
              @searchCommit="searchQuery"
              @searchFilter="searchQueryFilter"
              @searchClose="confirm"
              @searchClean="tableCleanJobs"
            />
          </span>
          <template slot-scope="text, record">
            {{
              record.EventDestination != "0"
                ? $t(
                    whereList.filter(
                      (item) => item.value === record.EventDestination
                    )[0].label
                  )
                : ""
            }}
          </template>
        </a-table-column>
        <!-- 状态 -->
        <a-table-column
          key="EventStatus"
          data-index="EventStatus"
          width="150px"
          @filterDropdownVisibleChange="
            (e) => {
              if (e) this.setValus(7);
            }
          "
        >
          <span slot="title">{{ $t("menu.list.table-list") }}</span>
          <span slot="filterDropdown" slot-scope="{ confirm }">
            <table-select
              ref="tableselect7"
              :filter-data="filterData"
              :singleSearch="false"
              @searchCommit="searchQuery"
              @searchFilter="searchQueryFilter"
              @searchClose="confirm"
              @searchClean="tableCleanJobs"
            />
          </span>
          <span
            slot-scope="text, record"
            :style="{
              color:
                record.EventStatus != '0'
                  ? statusList.filter(
                      (item) => item.value === record.EventStatus
                    )[0].color
                  : '',
            }"
          >
            {{
              record.EventStatus != "0"
                ? $t(
                    statusList.filter(
                      (item) => item.value === record.EventStatus
                    )[0].label
                  )
                : ""
            }}
          </span>
        </a-table-column>
        <!-- 创建人 -->
        <a-table-column
          key="EventCreatorStr"
          data-index="EventCreatorStr"
          width="150px"
          @filterDropdownVisibleChange="
            (e) => {
              if (e) this.setValus(8);
            }
          "
          :sorter="true"
        >
          <span slot="title">{{
            $t("breach.list.content.table.creator")
          }}</span>
          <span slot="filterDropdown" slot-scope="{ confirm }">
            <table-select
              ref="tableselect8"
              :filter-data="filterData"
              :singleSearch="true"
              @searchCommit="searchQuery"
              @searchFilter="searchQueryFilter"
              @searchClose="confirm"
              @searchClean="tableCleanJobs"
            />
          </span>
        </a-table-column>
        <!-- 创建时间 -->
        <a-table-column
          key="EventCreatetime"
          data-index="EventCreatetime"
          width="150px"
          @filterDropdownVisibleChange="
            (e) => {
              if (e) this.setValus(9);
            }
          "
          :sorter="true"
        >
          <span slot="title">{{
            $t("breach.list.content.table.createtime")
          }}</span>
          <span slot="filterDropdown" slot-scope="{ confirm }">
            <table-select
              ref="tableselect9"
              :filter-data="filterData"
              :singleSearch="false"
              @searchCommit="searchQuery"
              @searchFilter="searchQueryFilter"
              @searchClose="confirm"
              @searchClean="tableCleanJobs"
            />
          </span>
        </a-table-column>
        <!-- 操作 -->
        <a-table-column
          key="action"
          :title="$t('app.setting.othersettings')"
          width="150px"
          fixed="right"
        >
          <template slot-scope="text, record">
            <span>
              <a-dropdown :trigger="['click']">
                <a-button type="link" icon="more" />
                <template #overlay>
                  <a-menu>
                    <!-- 查看 -->
                    <a-menu-item @click="openDetail('view', record)">
                      <a-button type="link">{{ $t("risk.read") }}</a-button>
                    </a-menu-item>
                    <!-- 共享权限 -->
                    <a-menu-item
                      @click="addPermissionFn(record.Id)"
                      v-if="
                        record.EventStatus === 4 &&
                        record.EventProcessed === $store.state.user.info.YtId
                      "
                    >
                      <a-button type="link">{{
                        $t("user.verification-code.required1115661105722")
                      }}</a-button>
                    </a-menu-item>
                    <!-- 编辑 -->
                    <a-menu-item
                      @click="openDetail('edit', record)"
                      v-if="
                        record.EventStatus === 1 ||
                        (record.EventStatus === 3 &&
                          $store.state.user.info.AssignPersonnel === 1) ||
                        (record.EventStatus === 4 &&
                          (record.EventProcessed ===
                            $store.state.user.info.YtId ||
                            record.Role.BusinessUsers ||
                            record.Role.Collaborators ||
                            record.Role.ActionOwner ||
                            record.Role.ActionApproval ||
                            record.Role.Write)) ||
                        (record.EventStatus === 2 &&
                          record.EventProcessed === $store.state.user.info.YtId)
                      "
                    >
                      <a-button type="link">{{
                        $t("user.verification-code.required111566147")
                      }}</a-button>
                    </a-menu-item>
                    <!-- 删除 -->
                    <a-menu-item v-if="record.EventStatus === 1">
                      <a-popconfirm
                        :title="
                          $t('user.verification-code.required111566110577225')
                        "
                        :ok-text="$t('user.verification-code.required1166')"
                        :cancel-text="$t('user.email.required11')"
                        @confirm="() => deleteRow(record.Id)"
                      >
                        <a-button type="link">{{
                          $t("menu.exception.trigger")
                        }}</a-button>
                      </a-popconfirm>
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </span>
          </template>
        </a-table-column>
      </a-table>
      <add-permission ref="addPermission" />
      <a-modal
        :title="$t('breach.list.content.add.title')"
        width="30%"
        :visible="visible"
        :ok-text="$t('user.v15')"
        :cancel-text="$t('user.email.required11')"
        dialogClass="breach-modal"
        :confirmLoading="confirmLoading"
        @cancel="modalCancel"
        @ok="submit"
      >
        <a-form :form="form">
          <a-form-item>
            <a-select
              v-decorator="[
                'EventTemplate',
                {
                  rules: [
                    {
                      required: true,
                      message: $t(
                        'user.verification-code.required11156611057733900'
                      ),
                    },
                  ],
                },
              ]"
              :placeholder="
                $t('user.verification-code.required11156611057733900')
              "
            >
              <a-select-option v-for="item in sourceList" :key="item.value">{{
                $t(item.label)
              }}</a-select-option>
            </a-select>
            <a-tooltip placement="right">
              <template slot="title">
                <span>{{ $t("breach.list.content.add.tip") }}</span>
              </template>
              <a-icon type="question-circle" />
            </a-tooltip>
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </div>
</template>

<script>
import tableSelect from "@/components/tableSelect/tableSelect.vue";
import addPermission from "./components/addPermission.vue";
import { whereList } from "@/staticLists/breach";
import { createDataBreach } from "@/api/dataBreach/json";
import {
  changeStatus,
  deleteDataBreach,
  getDataBreachList,
  getGroup,
  getTotal,
} from "@/api/dataBreach/form";
import store from "@/store";
export default {
  name: "breachList",
  components: { tableSelect, addPermission },
  data() {
    return {
      cardList: [
        {
          url: "total",
          num: "50",
          title: "user.verification-code.required111566110577366",
        },
        {
          url: "draft",
          num: "2",
          title: "user.verification-code.required111566110577368",
        },
        {
          url: "toDistributed",
          num: "10",
          title: "breach.list.header.toDistributed",
        },
        {
          url: "assigned",
          num: "10",
          title: "breach.list.header.assigned",
        },
        {
          url: "inProcess",
          num: "10",
          title: "breach.list.header.inProcess",
        },
        {
          url: "completed",
          num: "18",
          title: "user.verification-code.required111566146",
        },
      ],
      listLoading: false,
      listData: [],
      setValusKey: -1,
      filterData: [],
      queryForm: {},
      kvMap: [
        "",
        "EventId",
        "EventShortDescription",
        "EventTemplate",
        "EventType",
        "EventProcessed",
        "EventDestination",
        "EventStatus",
        "EventCreator",
        "EventCreatetime",
      ],
      okyMap: [
        "",
        "EventIds",
        "EventShortDescriptions",
        "",
        "",
        "",
        "",
        "",
        "EventCreators",
      ],
      sourceList: [
        { label: "breach.list.content.table.source.breach", value: 1 },
        { label: "breach.list.content.table.source.dlp", value: 2 },
      ],
      lang: localStorage.getItem("lang").includes("zh-CN"),
      whereList,
      statusList: [
        {
          label: "user.verification-code.required111566110577368",
          value: 1, // 草稿
          color: "rgb(136, 136, 136)",
        },
        {
          label: "breach.list.header.assigned",
          value: 2, // 已分配
          color: "rgb(140, 215, 255)",
        },
        {
          label: "breach.list.header.toDistributed",
          value: 3, // 待分配
          color: "rgb(252, 202, 0)",
        },
        {
          label: "breach.list.header.inProcess",
          value: 4, // 处理中
          color: "rgb(80, 119, 165)",
        },
        {
          label: "user.v.required111566110577369",
          value: 5, // 已完成
          color: "rgb(129, 179, 55)",
        },
      ],
      visible: false,
      form: this.$form.createForm(this),
      total: 0,
      confirmLoading: false
    };
  },
  created() {
    store.dispatch("GetInfo");
    this.getList();
  },
  async mounted() {
    let that = this;
    window.addEventListener("setItemEvent", function (e) {
      if (e.key == "lang") {
        that.lang = JSON.parse(e.value) == "zh-CN";
      }
    });
    this.updateTotal();
  },
  methods: {
    // 查询Filter逻辑
    async setValus(typeId) {
      this.listLoading = true;
      try {
        const { data } = await getGroup({ condition: typeId });
        this.setValusKey = typeId;
        this.filterData = data;
        if (typeId === 3 || typeId === 7 || typeId === 6) {
          // 事件类型
          this.filterData.forEach((item) => {
            if (typeId === 3) {
              item.text = this.$t(
                this.sourceList.filter(
                  (source) => source.value === Number(item.text)
                )[0].label
              );
            } else if (typeId === 7) {
              item.text = this.$t(
                this.statusList.filter(
                  (status) => status.value === Number(item.text)
                )[0].label
              );
            } else if (typeId === 6) {
              // 数据泄露在何处
              item.text = this.$t(
                this.whereList.filter(
                  (where) => where.value === Number(item.text)
                )[0].label
              );
            }
          });
        }
      } catch (error) {
        this.$message.error(error);
      } finally {
        this.listLoading = false;
      }
    },
    async searchQuery(e) {
      this.queryForm[this.kvMap[this.setValusKey]] = undefined;
      this.queryForm = {
        ...this.queryForm,
        [this.okyMap[this.setValusKey]]: e,
      };
      await this.getList("filter");
    },
    async searchQueryFilter(e) {
      this.queryForm[this.okyMap[this.setValusKey]] = undefined;
      this.queryForm = {
        ...this.queryForm,
        [this.kvMap[this.setValusKey]]: e,
      };
      await this.getList("filter");
    },
    async tableCleanJobs(type) {
      if (type === "part") {
        this.queryForm[this.kvMap[this.setValusKey]] = undefined;
        this.queryForm[this.okyMap[this.setValusKey]] = undefined;
      } else {
        this.queryForm = {};
        for (let i = 1; i <= 9; i++) {
          let dom = this.$refs[`tableselect${i}`];
          if (dom) {
            dom.inputValue = "";
            dom.inputCheckValue = [];
          }
        }
      }
      this.inputValue = "";
      await this.getList();
    },
    async getList(pagination, _, sort) {
      let sortMap = {
        EventId: "EventIdSort",
        EventShortDescription: "EventNameSort",
        EventProcessedStr: "ProcessedSort",
        EventDestination: "EventDestinationSort",
        EventCreatorStr: "EventCreatorSort",
        EventCreatetime: "CreatedSort",
      };
      this.listLoading = true;
      let query = {
        page: pagination?.current || 1,
        pageSize: pagination?.pageSize || 10,
        ...this.queryForm,
      };
      // 正序倒序
      if (sort) {
        query[sortMap[sort.columnKey]] = sort.order === "ascend" ? 2 : 1;
      } else {
        query.IdSort = 1;
      }
      let { data } = await getDataBreachList(query);
      this.total = data.Total;
      this.listData = data.Lists;
      this.listLoading = false;
    },
    addPermissionFn(Id) {
      this.$refs.addPermission.open(Id);
    },
    submit() {
      this.form.validateFields(async (err, value) => {
        if (!err) {
          this.confirmLoading = true
          let res = await createDataBreach(value);
          if (res.code === 1) {
            this.$router.push({
              path: "/breach/register",
              query: { breachMode: value.EventTemplate, Id: res.data.Id },
            });
            this.confirmLoading = false
          }
        }
      });
    },
    modalCancel() {
      this.visible = false;
      this.form.resetFields();
    },
    openDetail(type, row) {
      if (
        type === "edit" &&
        row.EventProcessed === this.$store.state.user.info.YtId &&
        row.EventStatus === 2
      ) {
        changeStatus({
          Id: row.Id,
          BreachStatus: 4,
        });
      }
      this.$router.push({
        name: "breachRegister",
        params: {
          breachMode: row.source,
          ifCanEdit: type === "view" ? 0 : 1,
          Id: row.Id,
          role: row.Role,
        },
      });
    },
    async deleteRow(Id) {
      let res = await deleteDataBreach({ Id });
      if (res.code === 1) {
        this.$message.success(
          this.$t("user.verification-code.required111566110577133")
        );
        this.getList();
        this.updateTotal();
      }
    },
    async updateTotal() {
      let countMap = [
        "TotalCount",
        "Status1Count",
        "Status3Count",
        "Status2Count",
        "Status4Count",
        "Status5Count",
      ];
      let { data } = await getTotal();
      for (let index = 0; index < countMap.length; index++) {
        this.cardList[index].num = data[0][countMap[index]];
      }
      this.cardList;
    },
  },
};
</script>

<style lang="less" scoped>
.breach-list {
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    .card {
      display: flex;
      align-items: center;
      border-radius: 8px;
      padding: 20px;
      padding-right: 50px;
      .card-right {
        margin-left: 10px;
        h4 {
          font-size: 30px;
        }
        p {
          font-size: 16px;
          width: 50px;
          color: #999;
          white-space: nowrap;
        }
      }
    }
  }
}
</style>
<style lang="less">
.breach-modal {
  .ant-modal-header {
    border-bottom: 0;
  }
  .ant-select {
    width: 90%;
    margin-right: 20px;
  }
  .ant-modal-footer {
    border-top: 0;
  }
}
</style>